<template>
  <div class="content-header">
    <img :src="oemSiteInfo.sysLogoUrl" style="height: 30px">
    <div class="but-content">
      <div class="mch-app" @click="open()">获取{{ $SYS_NAME_MAP.MCH_APP }}APP/小程序</div>
    </div>
  </div>
  <div
    class="content-body"
    :style="[
      { background: 'url(' + oemSiteInfo.mch.loginPageBGImgUrl + ')' },
      { backgroundSize: 'cover' },
      { backgroundPosition: 'center top' },
      { backgroundRepeat: 'no-repeat' }
    ]"
  >
    <div class="content-main" :style="{ justifyContent: calcChildrenPosition() }">
      <div v-if="vdata.loginBgType ==1" class="banner-content" :style="{ order: calcPosition() }">
        <JeepayBanner :bannerList="vdata.bannerList" height="500px" />
      </div>
      <!-- 表单部分 start -->
      <div class="user-layout-content">
        <!-- 错误提示信息 -->
        <a-alert
          v-if="showLoginErrorInfo"
          type="error"
          showIcon
          style="margin-bottom: 24px"
          :message="showLoginErrorInfo"
        />
        <div class="main">
          <div class="tab-box">
            <div class="desc">商户登录</div>
            <div class="tab">
              <!-- 密码登录 -->
              <a
                v-if="tabSign !== 'password'"
                class="operation-class"
                :class="{ themeColor: tabSign === 'password' }"
                @click="tab('password')"
              >密码登录</a>
              <span v-if="tabSign !== 'password'&&tabSign !== 'message'" style="margin: 0 10px">|</span>
              <!-- 短信登录 -->
              <a
                v-if="tabSign !== 'message'"
                class="operation-class"
                :class="{ themeColor: tabSign === 'message' }"
                @click="tab('message')"
              >短信登录</a>
              <span v-if="tabSign !== 'QrCode'" style="margin: 0 10px">|</span>
              <a v-if="tabSign !== 'QrCode'" class="operation-class" @click="tab('QrCode')">扫码登录</a>
            </div>
          </div>

          <a-form
            v-if="tabSign === 'password'"
            ref="formPwdLogin"
            class="user-layout-login"
            :model="formState"
            :rules="loginrules"
            @submit="handleSubmit"
          >
            <a-form-item name="username" class="input-item">
              <login-text-up
                v-model:value="formState.username"
                :disabled="!vdata.googleIsShow"
                :isLogin="true"
                :placeholder="vdata.googleIsShow ? '登录名/手机号' : ''"
              />
            </a-form-item>

            <a-form-item name="password" class="input-item" style="margin-bottom: -20px !important">
              <login-text-up
                v-model:value="formState.password"
                :disabled="!vdata.googleIsShow"
                :isLogin="true"
                :placeholder="vdata.googleIsShow ? '密码' : ''"
                isPassword="password"
              />
            </a-form-item>

            <div class="code-body">
              <div class="code-layout" :class="{ googleShow: !vdata.googleIsShow }">
                <div class="code code-layout-item">
                  <a-form-item name="vercode" class="input-item">
                    <login-text-up v-model:value="formState.vercode" :isLogin="true" placeholder="图形验证码" />
                  </a-form-item>

                  <div class="code-img" style="position: relative; background: #ddd">
                    <img v-show="vercodeImgSrc" :src="vercodeImgSrc" @click="refVercode()">
                    <div v-show="isOverdue" class="vercode-mask" @click="refVercode()">
                      已过期 请刷新
                    </div>
                  </div>
                </div>
                <a-form-item v-if="!vdata.googleIsShow" name="mfaCode" class="input-item">
                  <login-text-up
                    v-model:value="formState.mfaCode"
                    style="width: 300px"
                    placeholder="安全码"
                    :isLogin="true"
                    :isGoogle="'false'"
                    class="code-layout-item"
                  />
                </a-form-item>
              </div>
            </div>
            <a-tag v-if="!vdata.googleIsShow" color="orange">您已开启虚拟MFA验证，请输入MFA动态安全码。</a-tag>
            <a-form-item style="margin-bottom: 30px">
              <!-- 自动登录 -->
              <!-- <a-checkbox v-model="isAutoLogin">自动登录</a-checkbox> -->

              <!-- 忘记密码 -->
              <a class="operation-class" style="float: right" @click="toForgetPwd">忘记密码?</a>
              <!-- 注册 -->
              <a class="operation-class" style="float: left" @click="toRegister">注册</a>
            </a-form-item>
          </a-form>
          <a-form
            v-if="tabSign === 'message'"
            ref="formLogin"
            class="user-layout-login"
            :model="formState"
            :rules="vdata.rules"
            @submit="handleSubmit"
          >
            <a-form-item name="phone" class="input-item">
              <login-text-up v-model:value="formState.phone" :isLogin="true" placeholder="手机号" />
            </a-form-item>
            <div class="code">
              <a-form-item name="code" class="input-item">
                <login-text-up v-model:value="formState.code" :isLogin="true" placeholder="请输入验证码" />
              </a-form-item>
              <div>
                <a-button
                  type="primary"
                  :disabled="vdata.isDisabled"
                  style="height: 40px; margin-left: 10px"
                  @click="sendSMS()"
                >
                  {{ vdata.codeBtnText }}
                </a-button>
              </div>
            </div>
            <div class="code">
              <a-form-item name="vercode" class="input-item" />
            </div>
            <a-form-item style="margin-bottom: 30px">
              <!-- 忘记密码 -->
              <a class="operation-class" style="float: right" @click="toForgetPwd">忘记密码?</a>
              <!-- 注册 -->
              <a class="operation-class" style="float: left" @click="toRegister">注册</a>
            </a-form-item>
          </a-form>
          <QrLogin v-if="tabSign === 'QrCode'" />
          <a-button
            v-if="tabSign !== 'QrCode'"
            size="large"
            type="primary"
            :loading="loginBtnLoadingFlag"
            style="width: 100%"
            @click="debounceTime"
          >
            {{ vdata.submitText }}
          </a-button>
        </div>
      </div>
      <!-- 表单部分end -->
    </div>
    <div class="content-footer">
      <JeepayFooterInfo />
    </div>
  </div>
  <previewImg ref="refPrevImg" />
</template>
<script setup lang="ts">
import { sendSmsCode, phoneLogin } from '@/api/login'
import { message } from 'ant-design-vue'
import { timeFix } from '@/utils/util'
import { vercode } from '@/api/login'
import { login,$getUploadImgSize } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
import router from '@/router'
import { ref, onMounted, reactive, getCurrentInstance, h } from 'vue'
import { useOem } from '@/store/modules/oem'
import { debounce } from '@/utils/throttle'
import QrLogin from './components/QrLogin.vue'
import previewImg from '@/layouts/components/previewImg.vue'
import JeepayFooterInfo from '@/components/link/JeepayUIComponents/JeepayFooterInfo/JeepayFooterInfo.vue'
import JeepayBanner from '@/components/link/JeepayUIComponents/JeepayBanner/JeepayBanner.vue'
// 获取网站信息
const oemSiteInfo = useOem().getSiteInfo()

let loginPosition = ref('') // 决定登录框水平位置 左中右？
let loginPageCardPosition = oemSiteInfo.mch.loginPageCardPosition
if (loginPageCardPosition === 'right') {
  loginPosition.value = 'flex-end'
} else if (loginPageCardPosition === 'center') {
  loginPosition.value = 'center'
} else if (loginPageCardPosition === 'left') {
  loginPosition.value = 'flex-start'
}

// 获取全局函数
const { $infoBox, $SYS_NAME_MAP } = getCurrentInstance()!.appContext.config.globalProperties

const userStore = useUserStore()
// 防抖函数
const debounceTime = debounce(handleSubmit, 500)
let isOverdue = ref(false) // 设置过期样式
let isAutoLogin = true // 是否是自动登录
let loginBtnLoadingFlag = ref(false) // 登录按钮是否显示 加载状态
let showLoginErrorInfo = ref('') // 是否显示登录错误面板信息
let timer: number = -1
let vercodeImgSrc = ref('') // 验证码图片
let vercodeToken = ref('') // 验证码验证token
const refPrevImg: any = ref(null) // 二维码 预览组件实例
let tabSign = ref('password')
let formLogin = ref()
let formPwdLogin = ref()

let formState: any = reactive({})
const vdata = reactive({
  googleIsShow: true, // 是否让谷歌输入框展示
  submitText: '登录',
  codeBtnText: '发送短信验证码',
  isDisabled: false,
  rules: {
    phone: [
      {
        required: true,
        pattern: /^1\d{10}$/,
        message: '请输入正确的手机号',
        trigger: 'blur'
      }
    ],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
  },
  bannerList: oemSiteInfo.mch?.bannerConfig ? JSON.parse(oemSiteInfo.mch?.bannerConfig) : [], //轮播数据
  loginBgType: oemSiteInfo.mch.loginBgType
})
const loginrules: any = reactive({
  username: [{ required: true, message: '请输入登录名/手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  vercode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { max: 4, message: '验证码长度错误', trigger: 'blur' }
  ]
})
onMounted(() => {
  refVercode()
})

// handler
function handleSubmit() {
  if (tabSign.value === 'password') {
    formPwdLogin.value
      .validate()
      .then(() => {
        // 请求登录
        loginBtnLoadingFlag.value = true
        passwordLogin()
      })
      .catch((error) => {
        console.log('error', error)
      })
  } else if (tabSign.value === 'message') {
    formLogin.value
      .validate()
      .then(() => {
        // 请求登录
        loginBtnLoadingFlag.value = true
        messageLogin()
      })
      .catch((error) => {
        console.log('error', error)
      })
  }
}
// 密码登录
function passwordLogin() {
  let loginParams = {
    username: formState.username,
    password: formState.password,
    vercode: formState.vercode,
    vercodeToken: vercodeToken.value,
    googleCode: formState.mfaCode
  }
  login(loginParams)
    .then((bizData) => {
      loginBtnLoadingFlag.value = false

      if (bizData['isMFA']) {
        vdata.submitText = '确认登录'
        vdata.googleIsShow = false
        delete loginrules?.vercode
        loginrules.mfaCode = [
          { required: true, message: '请输入安全码', trigger: 'blur' }
        ] as any
        return
      }

      userStore.putToken(bizData['iToken'])
      $getUploadImgSize().then(res=>{
            localStorage.setItem('uploadImgSize',res.applymentImgUploadSize)
          })
      router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        let lastLoginTimeStr = bizData['lastLoginTime']
          ? '上次登录时间：' + bizData['lastLoginTime']
          : ''
        $infoBox.notification.success({
          message: '欢迎',
          description: [
            h('p', `${timeFix()}，欢迎回来`),
            h('p', lastLoginTimeStr)
          ]
        })
      }, 1000)
      showLoginErrorInfo.value = ''

      // router.push('/merchant/list')
    })
    .catch((err) => {
      loginBtnLoadingFlag.value = false
      showLoginErrorInfo.value = err.msg || JSON.stringify(err)
    })
}

// 短信登录
function messageLogin() {
  let loginParams = {
    phone: formState.phone,
    code: formState.code
  }
  phoneLogin(loginParams)
    .then((bizData) => {
      loginBtnLoadingFlag.value = false
      userStore.putToken(bizData['iToken'])
      $getUploadImgSize().then(res=>{
            localStorage.setItem('uploadImgSize',res.applymentImgUploadSize)
          })
      router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        let lastLoginTimeStr = bizData['lastLoginTime']
          ? '上次登录时间：' + bizData['lastLoginTime']
          : ''
        $infoBox.notification.success({
          message: '欢迎',
          description: [
            h('p', `${timeFix()}，欢迎回来`),
            h('p', lastLoginTimeStr)
          ]
        })
      }, 1000)
      showLoginErrorInfo.value = ''
    })
    .catch((err) => {
      loginBtnLoadingFlag.value = false
      showLoginErrorInfo.value = err.msg || JSON.stringify(err)
    })
}

// 切换密码登录
function tab(sign) {
  tabSign.value = sign
}

function refVercode() {
  // 刷新图片验证码
  // 获取图形验证码
  vercode().then((res) => {
    vercodeImgSrc.value = res.imageBase64Data
    vercodeToken.value = res.vercodeToken

    isOverdue.value = false

    if (timer) clearInterval(timer) // 如果多次点击则清除已有的定时器
    // 超过60秒提示过期刷新
    timer = window.setInterval(() => {
      res.expireTime--
      if (res.expireTime <= 0) {
        isOverdue.value = true
        clearInterval(timer)
      }
    }, 1000)
  })
}


function sendSMS() {
  // 发送短信验证
  if (!formState.phone) {
    return message.error('请输入手机号！')
  }
  // 校验手机号
  const reg = /^[1][0-9]{10}$/
  if (!reg.test(formState.phone)) {
    return message.error('请输入正确的手机号！')
  }
  vdata.isDisabled = true

  sendSmsCode({ phone: formState.phone, smsType: 'auth' })
    .then((res) => {
      return message.success('发送成功！')
    })
    .catch((err) => {
      vdata.isDisabled = false
      showLoginErrorInfo = err.msg || JSON.stringify(err)
      loginBtnLoadingFlag.value = false
      // 出错后三秒停止计时
      setTimeout(() => {
        if (timer) clearInterval(timer)
        vdata.isDisabled = false
        vdata.codeBtnText = '发送短信验证码'
      }, 500)
    })

  let time = 60 // 重发验证码时间
  vdata.codeBtnText = `${time}秒后重新发送`
  const timer = setInterval(() => {
    time -= 1
    vdata.codeBtnText = `${time}秒后重新发送`
    if (time === 0) {
      clearInterval(timer)
      vdata.isDisabled = false
      vdata.codeBtnText = '发送短信验证码'
    }
  }, 1000)
}

// 忘记密码跳转页面
function toForgetPwd() {
  router.push({ name: 'forget', path: '/user/forget' })
}

// 注册页面
function toRegister() {
  router.push({ name: 'register', path: '/user/register' })
}

// 监听回车事件
document.onkeydown = function (e) {
  var theEvent = e || window.event
  var code = theEvent.keyCode || theEvent.which || theEvent.charCode
  if (code == 13) {
    //回车键的键值为13
    debounceTime()
  }
}
const open = () => {
  refPrevImg.value.open()
}
const calcPosition = () => {
  return loginPosition.value == 'center' ? 1 : loginPosition.value == 'left' ? 1 : 0
}
const calcChildrenPosition = () => {
  return vdata.loginBgType == 1 ? 'space-between' : loginPosition.value
}
</script>

<style lang="less" scoped>
// 去除浏览器默认填充数据时，输入框的背景色
/deep/ input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill {
  box-shadow: inset 0 0 0 1000px #fff !important;
}

// 新布局
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  z-index: 100;
  padding: 0 50px;
  left: 0;
  right: 0;
  height: 80px;
  background-color: hsla(100, 100, 100, 0.85);
  backdrop-filter: blur(50px) saturate(180%);
}

.content-body {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  object-fit: cover;
  padding: 0 10vw;
  padding-top: 80px;
  min-height: 100vh;

  .content-main {
    flex-grow: 1;
    display: flex;
    
    align-items: center;
    // flex-direction: row-reverse;
    .banner-content {
      // flex: 1;
      // order: 1;
      width: 50vw;
    }
  }
}

// 表单部分样式
.user-layout-content {

  transition: 0.3s ease;

  input {
    height: 40px !important;
  }

  .main {
    padding: 35px 30px;
    box-sizing: border-box;
    min-width: 360px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    background: #fff;
    box-shadow: 0 30px 60px -35px rgb(0 0 0 / 10%);
    border: 1px solid #e7eaf3;
    align-items: center;
    border-radius: 15px;
    transition: all 0.3s, border 0s ease;

    .ant-form {
      max-width: 300px;
    }

    .tab-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 35px;
    }

    .desc {
      font-weight: bold;
      font-size: 20px;
      letter-spacing: 0.04em;
      color: var(--ant-primary-color);
      text-align: center;
    }

    .input-item {
      height: 65px;
      margin: 0 !important;
    }
  }

  .footer {
    // position: absolute;
    width: 100%;
    bottom: 0;
    padding: 0 16px;
    margin: 48px 0 24px;
    text-align: center;

    .links {
      margin-bottom: 8px;
      font-size: 14px;

      a {
        color: rgba(0, 0, 0, 0.45);
        transition: all 0.3s;

        &:not(:last-child) {
          margin-right: 40px;
        }
      }
    }

    .copyright {
      color: rgba(0, 0, 0, 0.45);
      font-size: 14px;
    }
  }
}

//登录页响应式的调整
@media screen and (min-width: 769px) and (max-width: 1024px) {
  .container {
    padding: 0 100px;
    min-height: 700px;

    .user-layout-content {
      width: 360px;
      height: auto;

      .main {
        width: 360px;
        box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
        border: 0.0625rem solid #e7eaf3;
        height: auto;
        justify-content: center;
        border-radius: 10px;
      }
    }
  }
}

@media screen and (min-width: 1025px) and (max-width: 1366px) {
  .container {
    padding: 0 150px;
    min-height: 700px;

    .user-layout-content {
      width: 360px;
      height: auto;

      .main {
        width: 360px;
        box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
        border: 0.0625rem solid #e7eaf3;
        height: auto;
        justify-content: center;
        border-radius: 10px;
      }
    }
  }
}

@media screen and (min-width: 1367px) and (max-width: 1600px) {
  .container {
    padding: 0 250px;
    min-height: 700px;

    .user-layout-content {
      width: 360px;
      height: auto;

      .main {
        width: 360px;
        box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
        border: 0.0625rem solid #e7eaf3;
        height: auto;
        justify-content: center;
        border-radius: 10px;
      }
    }
  }
}

@media screen and (min-width: 1601px) {
  .container {
    padding: 0 300px;
    min-height: 700px;

    .user-layout-content {
      width: 360px;
      height: auto;

      .main {
        width: 360px;
        box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
        border: 0.0625rem solid #e7eaf3;
        height: auto;
        justify-content: center;
        border-radius: 10px;
      }
    }
  }
}

.code-body {
  padding-top: 20px;
  width: 300px;
  overflow-x: hidden;
}

.code-layout {
  display: flex;
  width: 600px;
  transition: 0.3s;

  .code-layout-item {
    width: 50%;
  }
}

.googleShow {
  margin-left: -300px;
}

</style><style lang="less" scoped>.tab {
  .operation-class {
    color: #b0afb3;
  }
}

.themeColor {
  color: var(--ant-primary-color);
}

.user-layout-login {
  label {
    font-size: 14px;
  }

  .operation-class {
    font-size: 14px;
    color: @jee-theme;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }

  .code {
    display: flex;
    justify-content: space-between;

    .code-input {
      width: 216px;
    }

    .code-img {
      width: 120px;
      height: 40px;
      background-color: #ddd;
      margin-left: 10px;

      img {
        width: 120px;
        height: 40px;
      }
    }
  }

  .submit {
    margin-bottom: 0;
  }
}

.vercode-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.8;
  text-align: center;
  line-height: 40px;
  color: #fff;

  &:hover {
    cursor: pointer;
  }
}

.but-content {
  display: flex;
  .mch-app {
    background-color: rgba(0, 0, 0, .03);
    color: #666;
    border-radius: 5px;
    padding: 8px 28px;
    cursor: pointer;
  }

}
</style>
